export default {
    namespaced: true,
    state: [],
    mutations: {
        // state中的数据初始化
        init(state) {
            let jsonStr = localStorage.getItem('shopCart');
            jsonStr && state.push(...JSON.parse(jsonStr));
        },
        // 将商品添加到购物车，如果商品已存在，则修改数量
        add(state, goodsInfo) {
            // { id, count, price, selected }
            let index = state.findIndex(item => item.id === goodsInfo.id);
            if (index === -1) {
                state.push(goodsInfo);
            } else {
                state[index].count = goodsInfo.count;
            }
            localStorage.setItem('shopCart', JSON.stringify(state));
        },
        // 修改
        update(state, payload) {
            state.some(item => {
                if (item.id === payload.id) {
                    item[payload.key] = payload.value;
                    return true;
                }
            });
            localStorage.setItem('shopCart', JSON.stringify(state));
        },
        // 删除商品
        delete(state, id) {
            state.some((item, i) => {
                if (item.id === id) {
                    state.splice(i, 1);
                    return true;
                }
            });
            localStorage.setItem('shopCart', JSON.stringify(state));
        }
    },
    getters: {
        // 根据传入的id获取对应的商品数量
        getCount(state) {
            return (id) => {
                let goods = state.find(item => item.id === id);
                return goods ? goods.count : 0;
            };
        },
        // 获取购物车中已勾选商品的总数量和总价格
        getCountAndAmount(state) {
            let obj = { count: 0, selectedCount: 0, selectedAmount: 0 };
            state.forEach(item => {
                obj.count += item.count;
                if (item.selected) {
                    obj.selectedCount += item.count;
                    obj.selectedAmount += item.count * item.price;
                }
            });
            return obj;
        }
    }
}